package com.hqyj.lls.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.lls.entity.MhSelect;
import com.hqyj.lls.entity.User;
import com.hqyj.lls.entity.UserVO;
import com.hqyj.lls.mapper.UserMapper;
import com.hqyj.lls.service.UserService;
import com.hqyj.lls.utils.ResultUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService  {

    @Autowired
    private UserMapper userMapper;

    /* ##################################################获取用户所有信息和他的角色############################################# */


    @Override
    public ResultUtils userList(User user) {
        //开启分页
        PageHelper.startPage(user.getPage(),user.getNum());
        //获取用户所有数据
        List<User> users = userMapper.selectAll();

        //遍历所获取到的user对象信息
        for (int i = 0; i < users.size(); i++) {
            String username = users.get(i).getUsername();
            //根据用户名查出相应的角色
            List<String> rnames = userMapper.selectRolesByUsername(username);
            //将list<String>转换成字符串
            String str = rnames.stream().map(String -> String.toString()).collect(Collectors.joining(","));
            users.get(i).setRname(str);
        }
        PageInfo list = new PageInfo(users);
        HashMap<String, Object> map = new HashMap<>();
        map.put("totalPage",list.getPages()); //总页数
        map.put("list",list.getList()); //每页显示的数据
        map.put("total",list.getTotal()); //总条数
        return new ResultUtils(200,"",map);
    }


    //查询逻辑删除后的用户
    @Override
    public ResultUtils userdelList(User user) {
        PageHelper.startPage(user.getPage(),user.getNum());
        List<User> users = userMapper.selectDelUser(user);
        PageInfo<User> info = new PageInfo<>(users);
        HashMap<String, Object> map = new HashMap<>();
        map.put("totalPage",info.getPages()); //总页数
        map.put("list",info.getList()); //每页显示的数据
        map.put("total",info.getTotal()); //总条数
        return new ResultUtils(200,"",map);
    }

    //恢复逻辑删除后的用户
    public ResultUtils changeDel(User user){
        userMapper.changeDel(user);
        return new ResultUtils(200,"恢复成功",null);
    }

    @Override
    public ResultUtils mhuserdelList(User user) {
        List<User> users = userMapper.mhselectDelUser(user);
        PageHelper.startPage(user.getPage(),user.getNum());
        System.out.println(user.getPage());
        PageInfo<User> info = new PageInfo<>(users);
        HashMap<String, Object> map = new HashMap<>();
        map.put("totalPage",info.getPages()); //总页数
        map.put("list",info.getList()); //每页显示的数据
        map.put("total",info.getTotal()); //总条数
        return new ResultUtils(200,"",map);
    }


    @Override //登录
    public ResultUtils login(User user) {
        try {
            //0.判断当前用户名密码是否为空
            if (user.getUsername() == "" || user.getPassword() == "") return new ResultUtils(500,"用户名或密码不能为空",null);
            //1.获取当前用户对象主体
            Subject subject = SecurityUtils.getSubject();
            //2.将请求参数封装在token中
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            //3.完成登录
            subject.login(token);
            //把登录的用户名存入到session中，并设置名为loginUserName
            subject.getSession().setAttribute("loginUserName",user.getUsername());
        } catch (UnknownAccountException e) {
            return new ResultUtils(500,"用户名不存在",null);
        } catch (IncorrectCredentialsException e){
            return new ResultUtils(500,"密码不对",null);
        }
        return new ResultUtils(200,"登录成功",null);
    }

    @Override
    public ResultUtils loginout() {
        //获得subject主体
        Subject subject = SecurityUtils.getSubject();
        //清除缓存
        subject.logout();
        return new ResultUtils(200,"",null);
    }

    @Override //模糊查询
    public ResultUtils mhselect(MhSelect mhSelect) {
        //开启分页
        PageHelper.startPage(mhSelect.getPage(),mhSelect.getNum());
        //获取用户所有数据
        List<MhSelect> selectmh = userMapper.selectmh(mhSelect);
        //遍历所获取到的user对象信息
        for (int i = 0; i < selectmh.size(); i++) {
            String username = selectmh.get(i).getUsername();
            //根据用户名查出相应的角色
            List<String> rnames = userMapper.selectRolesByUsername(username);
            //将list<String>转换成字符串
            String str = rnames.stream().map(String -> String.toString()).collect(Collectors.joining(","));
            selectmh.get(i).setRname(str);
        }
        PageInfo list = new PageInfo(selectmh);
        HashMap<String, Object> map = new HashMap<>();
        map.put("totalPage",list.getPages()); //总页数
        map.put("list",list.getList()); //每页显示的数据
        map.put("total",list.getTotal()); //总条数
        return new ResultUtils(200,"",map);
    }

    //注册
    @Override
    public ResultUtils register(User user) {
        if (user.getUsername() == "" || user.getPassword() == "") return new ResultUtils(500,"注册用户名或密码不能为空",null);
        //查询该用户是否存在
        User userone = userMapper.selectOneByUsername(user.getUsername());
        if (userone!=null){
            return new ResultUtils(500,"用户已存在",null);
        }else {
            user.setDeleted(0);
            user.setJoinDate(new Date());
            Integer insert = userMapper.insret(user);
            if (insert>0){
                return new ResultUtils(200,"注册成功",null);
            }else {
                return new ResultUtils(500,"数据出错,请稍后注册",null);
            }
        }

    }

    //批量恢复
    @Override
    public ResultUtils changeDelUserAll(User user) {
        String conUserId = user.getConUserId();
        //将连接的用户id字符串转换为list集合
        String[] split = conUserId.split(",");
        List<String> list = Arrays.asList(split);
        Integer integer = userMapper.changeDelUserAll(list);
        if (integer>0){
            return new ResultUtils(200,"批量恢复成功",null);
        }else {
            return new ResultUtils(200,"批量恢复失败",null);
        }

    }

    //批量删除
    public ResultUtils delUserAndRoleAll(User user){
        String conUserId = user.getConUserId();
        String[] split = conUserId.split(",");
        List<String> list = Arrays.asList(split);
        //删除用户
        userMapper.delUserAll(list);
        //删除角色
        userMapper.delRoleAll(list);
        return new ResultUtils(200,"批量删除成功",null);
    }

    @Override
    public ResultUtils managerList() {
        Subject subject = SecurityUtils.getSubject();
        String string = (String) subject.getSession().getAttribute("loginUserName");
        User user1 = userMapper.selectOneByUsername(string);
        return new ResultUtils(200,"",user1);
    }


    //添加
    @Override
    public ResultUtils insert(User user) {
        user.setDeleted(0);
        user.setJoinDate(new Date());
        userMapper.insret(user);
        Integer userId = userMapper.selectUserId(user.getUsername());
        String rname = user.getRname();
        if (rname.equals("admin,simple")==true){
            //根据用户id角色添加1,2
            userMapper.insertasimpleByuserId(userId);
            userMapper.insertadminByuserId(userId);
        }else if (rname.equals("simple")==true){
            userMapper.insertasimpleByuserId(userId);
        }else if (rname.equals("admin")){
            userMapper.insertasimpleByuserId(userId);
            userMapper.insertadminByuserId(userId);
        }else {
            userMapper.insertasimpleByuserId(userId);
        }
        return new ResultUtils(200,"已添加成功",null);
    }

    //修改
    @Override
    public ResultUtils update(User user) {
        Integer userId = user.getUserId();
        //先根据userId删除对应的角色
        userMapper.deleteRoleByuserId(user.getUserId());
        String rname = user.getRname();
        if (rname.equals("admin,simple")==true){
        //根据用户id角色添加1,2
            userMapper.insertasimpleByuserId(userId);
            userMapper.insertadminByuserId(userId);
        }else if (rname.equals("simple")==true){
            userMapper.insertasimpleByuserId(userId);
        }else if (rname.equals("admin")){
            userMapper.insertasimpleByuserId(userId);
            userMapper.insertadminByuserId(userId);
        }else {
            userMapper.insertasimpleByuserId(userId);
        }
        user.setJoinDate(new Date());
        user.setDeleted(0);
        //修改用户user数据
        userMapper.update(user);
        return new ResultUtils(200,"修改成功",null);
    }

    //真实删除用户及其对应的角色
    @Override
    public ResultUtils realDelUserAndRole(User user) {
        //1.根据userid删除user
        userMapper.deleteByUserId(user.getUserId());
        //2.根据userid删除role
        userMapper.deleteRoleByuserId(user.getUserId());
        return new ResultUtils(200,"删除成功",null);
    }


    @Override
    public ResultUtils deleteUpdByUserId(User user) {
        userMapper.deleteUpdByUserId(user.getUserId());
        return new ResultUtils(200,"删除成功",null);
    }


}
